package com.ay.weixin.fdc.boss.autoreply.event;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletException;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.lizar.config.Config;
import org.lizar.config.keys.Keys;
import org.lizar.controller.Event;
import org.lizar.controller.loader.EventLoader;
import org.lizar.ioc.Container;
import org.lizar.json.JList;
import org.lizar.json.JObject;
import org.lizar.json.util.JSONParser;
import org.lizar.util.StringHelper;
import org.lizar.util.https.Https;

import com.ay.weixin.autoreply.db.IbatisAutoReplyDao;
import com.ay.weixin.autoreply.db.IbatisAutoReplyNewsDao;
import com.ay.weixin.autoreply.domain.AccessTokenModule;
import com.ay.weixin.autoreply.domain.Message;
import com.ay.weixin.autoreply.domain.MsgNews;
import com.ay.weixin.autoreply.event.handle.HandleInput;
import com.ay.weixin.config.ProjectConfig;
import com.ay.weixin.config.group.exception.ProjectNotExists;
import com.ay.weixin.config.group.exception.ProjectVarNotExists;
import com.ay.weixin.fdc.admin.customer.domain.Customer;
import com.ay.weixin.fdc.boss.customer.event.CustomerLogin;

public class ReplySetting extends Event {

	private IbatisAutoReplyDao auto_reply_dao;
	private IbatisAutoReplyNewsDao auto_reply_news_dao;
	private AccessTokenModule acess_token;
	
	@Override
	public void init_property() throws Exception {
		auto_reply_dao=Container.get(IbatisAutoReplyDao.class);
		auto_reply_news_dao=Container.get(IbatisAutoReplyNewsDao.class);
		acess_token=Container.get(AccessTokenModule.class);
		
		

		
	}

	public static String getRelatImagePath(EventLoader el,long project_id,String file_name){
		return Keys.getStr("auto_reply.image_file_upload_foler")+"/"+project_id+"/"+new Date().getDate()+"/"+file_name;
	}
	
	public static String getImagePath(EventLoader el,long project_id,String file_name){
		return el.getRealPath(Keys.getStr("auto_reply.image_file_upload_foler")+"/"+project_id+"/"+new Date().getDate()+"/"+file_name);
	}
	
	@Override
	public String default_handling_path() {
		return "/reply/*";
	}

	@Override
	public void handle(EventLoader el) throws ServletException, IOException, ProjectNotExists, ProjectVarNotExists {
		Customer customer=(Customer)el.getSessionAttr("customer");
		if(customer==null){
			el.response_to_root(CustomerLogin.login_path());
			return;
		}
		try {
			if(el.queryPathCheck(1,"")){
				reply(el,customer.getWxprojectID());
			}else if(el.queryPathCheck(1,"add_text")){
				add_text(el,customer.getWxprojectID());
			}else if(el.queryPathCheck(1,"update_text")){
				update_text(el,customer.getWxprojectID());
			}else if(el.queryPathCheck(1,"delete_text")){
				delete_text(el,customer.getWxprojectID());
			}else if(el.queryPathCheck(1,"add_new_news")){
				add_new_news(el,customer.getWxprojectID());
			}else if(el.queryPathCheck(1,"update_news")){
				update_news(el,customer.getWxprojectID());
			}else if(el.queryPathCheck(1,"delete_news")){
				delete_news(el,customer.getWxprojectID());
			}else if(el.queryPathCheck(1,"setting")){
				setting(el,customer.getWxprojectID());
			}else if(el.queryPathCheck(1,"recheck_r_weixin_info")){
				recheck_r_weixin_info(el,customer.getWxprojectID());
			}
		} catch (SQLException e) {
			e.printStackTrace();
			reply(el,customer.getWxprojectID());
			return;
		}
		
	}
	
	
	private void recheck_r_weixin_info(EventLoader el,long wxproject_id) throws IOException{
		String token=acess_token.getAccessToken(wxproject_id);
		String result=null;
		try {
			result=Https.GetMethod("https://api.weixin.qq.com/cgi-bin/user/get?access_token="+token);
		} catch (Exception e) {
			e.printStackTrace();
			el.text(e.getLocalizedMessage());
			return;
		}
		JObject body=null;
		
		body=(JObject) JSONParser.parse(result);
		
		if(body==null){
			el.text("用户粉丝结果解析错误:"+result);
			return;
		}
		body=body._entity("data");
		if(body==null){
			el.text("用户粉丝结果解析错误2:"+result);
			return;
		}
		
		JList openid_list=body._list("openid");
		
		if(openid_list!=null&&!openid_list.isEmpty()){
			for(Object obj:openid_list){
				HandleInput.fetch_user_info(wxproject_id,obj.toString(),"input");
			}
		}
		el.text("用户粉丝信息更新成功!");
	}
	
	private void setting(EventLoader el,long wxproject_id) throws IOException, ServletException, ProjectNotExists, ProjectVarNotExists{
		boolean default_msg_reply=el.getBool("default_msg_reply");
		String msg=null;
		try {
			ProjectConfig.update(wxproject_id, "weixin_api_auto_reply.default_msg_reply", default_msg_reply);
		} catch (Exception e) {
			e.printStackTrace();
			msg=el.i18("replysetting.default_msg_reply.failured")+":"+e.getMessage();
		}
		
		el.setAttr("msg",msg);
		
		reply(el,wxproject_id);
		
	}
	
	private void reply(EventLoader el,long wxproject_id) throws IOException, ServletException{
		String msg=el.getAttr("msg",null);
		String event=el.getAttr("event",el.getStr("event", "default_msg_reply"));
		
		
		if(StringHelper.equals(event, Keys.getStr("input_message_event_type.subscribe"))){
			Message subscribe=null;
			try {
				subscribe=auto_reply_dao.getEventMessage(wxproject_id,Keys.getStr("input_message_event_type.subscribe"),"event");
			} catch (SQLException e) {
				e.printStackTrace();
				msg=el.i18("replysetting.msg.bind.db.failure");
				el.setAttr("msg",msg);
				el.template("/WEB-INF/template/boss/reply/index.vm");
				return;
				
			}
			el.setAttr("reply_msg", subscribe);
			if(subscribe!=null){
				if(StringHelper.equals(subscribe.getResponse_type(), "news")){
					List<MsgNews> nlist=null;
					try {
						nlist=auto_reply_news_dao.getNewsList(wxproject_id,subscribe.getId());
					} catch (SQLException e) {
						e.printStackTrace();
						msg=el.i18("replysetting.msg.bind.db.failure");
						el.setAttr("msg",msg);
						el.template("/WEB-INF/template/boss/reply/index.vm");
						return;
					}
					el.setAttr("reply_news", nlist);
					
				}
			}
		}else{
			Message default_msg=null;
			try {
				default_msg=auto_reply_dao.getEventMessage(wxproject_id,"default_msg_reply","text");
			} catch (SQLException e) {
				e.printStackTrace();
				msg=el.i18("replysetting.msg.bind.db.failure");
				el.setAttr("msg",msg);
				el.template("/WEB-INF/template/boss/reply/index.vm");
				return;
			}
			el.setAttr("reply_msg", default_msg);
			if(default_msg!=null){
				if(StringHelper.equals(default_msg.getResponse_type(), "news")){
					List<MsgNews> nlist=null;
					try {
						nlist=auto_reply_news_dao.getNewsList(wxproject_id,default_msg.getId());
					} catch (SQLException e) {
						e.printStackTrace();
						msg=el.i18("replysetting.msg.bind.db.failure");
						el.setAttr("msg",msg);
						el.template("/WEB-INF/template/boss/reply/index.vm");
						return;
					}
					el.setAttr("reply_news", nlist);
				}
			}
		}
		
		el.setAttr("msg",msg);
		el.setAttr("event",event);
		el.setAttr("default_msg_reply",ProjectConfig._bool(wxproject_id,"weixin_api_auto_reply.default_msg_reply"));
		
		el.template("/WEB-INF/template/boss/reply/index.vm");
	}
	
	

	private void add_new_news(EventLoader el,long wxproject_id) throws IOException, ServletException, SQLException{
		String msg=null;
        //检查输入请求是否为multipart表单数据。
        boolean isMultipart = ServletFileUpload.isMultipartContent(el.request());
        if(!isMultipart){
        	el.response_to_root("/reply");
        	return;
        }
        Map<String,String> params=new HashMap<String,String>();
        String file_name=UUID.randomUUID().toString()+".jpg";
        String file_path=ReplySetting.getImagePath(el,wxproject_id, file_name);
        File savedFile=null;
        boolean file_uploaded=false;
        /**为该请求创建一个DiskFileItemFactory对象，通过它来解析请求。执行解析后，所有的表单项目都保存在一个List中。**/
        try {
            DiskFileItemFactory factory = new DiskFileItemFactory();
            factory.setSizeThreshold(4096); // 设置缓冲区大小，这里是4kb
            File cache_dir=new File(el.getRealPath("/WEB-INF/lizar/file_pos_form_cache"));
            if(!cache_dir.exists())cache_dir.mkdirs();
            factory.setRepository(cache_dir);// 设置缓冲区目录
            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setHeaderEncoding("utf-8");//解决文件乱码问题
            upload.setSizeMax(ProjectConfig.getLong(wxproject_id,"sys.max_image_file_size")*1024);// 设置最大文件尺寸
            List<FileItem> items = upload.parseRequest(el.request());
            if(items==null||items.isEmpty()){
            	  msg=el.i18("replysetting.news.image.upload.nofile.found");
            	  el.setAttr("msg",msg);
                  reply(el,wxproject_id);
                  return;
            }
            Iterator<FileItem> itr = items.iterator();//所有的表单项
            while (itr.hasNext()){
                 FileItem item = (FileItem) itr.next();//循环获得每个表单项
                 if(item.isFormField()){
                	 params.put(item.getFieldName(), new String(item.get(),"utf-8"));
                	 System.out.println(item.getFieldName()+"="+ new String(item.get(),"utf-8"));
                	 continue;
                 }
                 String name = item.getName();//获得文件名 包括路径啊
                 if(name.toLowerCase().endsWith(".jpg")){
                     savedFile=new File(file_path);
                     if(!savedFile.getParentFile().exists()){
                    	 savedFile.getParentFile().mkdirs();
                     }
                     item.write(savedFile);
                     file_uploaded=true;
                     break;
                 }
            }
        } catch (Exception e) {
            msg=el.i18("replysetting.news.image.upload.failed");
            e.printStackTrace();
            el.setAttr("msg",msg);
            reply(el,wxproject_id);
            return;
        }
		
        if(!file_uploaded){
        	 msg=el.i18("replysetting.news.image.upload.nofile.found");
        	 el.setAttr("msg",msg);
        	 reply(el,wxproject_id);
             return;
        }
        String description=params.get("description");
        if(description==null)description="";
        String event=params.get("event");
		String title=params.get("title");
		String msg_type=params.get("msg_type");
		if(msg_type==null)msg_type="event";
		el.setAttr("event",event);
		
		String url=params.get("url");
		
		if(StringHelper.isNull(event)){
			el.response_to_root("/reply");
			return;
		}
		
		if(description.length()>Keys.getInt("auto_reply.news_msg_description_length")){
			msg=String.format(el.i18("replysetting.news.description.max.length.exceed"),Keys.getInt("auto_reply.news_msg_description_length"));
			el.setAttr("msg",msg);
			reply(el,wxproject_id);
			return;
		}
		
		if(title==null){
			msg=el.i18("menu.news.title.cannot.be.empty");
			el.setAttr("msg",msg);
			reply(el,wxproject_id);
			return;
		}
		
		if(title.length()>Keys.getInt("auto_reply.news_msg_title_length")){
			msg=String.format(el.i18("replysetting.news.title.max.length.exceed"),Keys.getInt("auto_reply.news_msg_title_length"));
			el.setAttr("msg",msg);
			reply(el,wxproject_id);
			return;
		}
		
		if(url==null){
			msg=el.i18("replysetting.news.url.cannot.be.empty");
			el.setAttr("msg",msg);
			reply(el,wxproject_id);
			return;
		}
		
		if(url.length()>Keys.getInt("auto_reply.url_max_length")){
			msg=String.format(el.i18("replysetting.news.url.max.length.exceed"),Keys.getInt("auto_reply.url_max_length"));
			el.setAttr("msg",msg);
			reply(el,wxproject_id);
			return;
		}
		
		Message message=auto_reply_dao.getEventMessage(wxproject_id,event,msg_type);
		if(message!=null){
			int size=auto_reply_news_dao.size_by_id(wxproject_id,message.getId());
			if(size>=Keys.getInt("auto_reply.one_msg_max_news")){
				 msg=String.format(el.i18("replysetting.news.max.news.number.exceed"),Keys.getInt("auto_reply.one_msg_max_news"));
				 el.setAttr("msg",msg);
				 reply(el,wxproject_id);
	             return;
			}
			if(!StringHelper.equals(message.getResponse_type(), "news")){
				auto_reply_dao.update_response_type(message.getResponse_type(),message.getId());
			}
		}else{
			message =new Message();
			message.setEvent(event);
			message.setMsg_type(msg_type);
			message.setResponse_type("news");
			auto_reply_dao.insert(message);
			message=auto_reply_dao.getEventMessage(wxproject_id,event,msg_type);
		}
		
		MsgNews msg_news=new MsgNews();
		msg_news.setArticle_count(0);
		msg_news.setAuto_reply_id(message.getId());
		msg_news.setDescription(description);
		msg_news.setTitle(title);
		msg_news.setUrl(url);
		msg_news.setWxproject_id(wxproject_id);
		msg_news.setPos(auto_reply_news_dao.getMaxPosByAutoReplyId(wxproject_id,message.getId()));
		msg_news.setPic_url(ReplySetting.getRelatImagePath(el,  wxproject_id,file_name));
		auto_reply_news_dao.insert(msg_news);
		
		if(msg==null){
			msg=el.i18("replysetting.news.add.success");
		}
		el.setAttr("msg", msg);
		
		reply(el,wxproject_id);
		
	}
	
	private void delete_news(EventLoader el,long wxproject_id) throws IOException, ServletException, SQLException{
		String event=el.getStr("event");
		long news_id=el.getLong("id");
		String msg=null;
		if(StringHelper.isNull(event)){
			el.response_to_root("/reply");
			return;
		}
		MsgNews msg_news=auto_reply_news_dao.getById(news_id);
		if(msg_news==null){
			msg=el.i18("replysetting.news.message.not.exist");
			el.setAttr("msg", msg);
			reply(el,wxproject_id);
			return;
		}
		String pic_url=msg_news.getPic_url();
		File f=new File(el.getRealPath(pic_url));
		System.out.println(f.getPath());
		
		auto_reply_news_dao.delete_by_id(news_id);
		
		Message message=auto_reply_dao.getById(msg_news.getAuto_reply_id());
		
		if(message!=null){
			int size=auto_reply_news_dao.size_by_id(wxproject_id,message.getId());
			if(size==0){
				auto_reply_dao.delete_by_id(message.getId());
			}
		}
		
		f.delete();
		msg=el.i18("replysetting.news.message.delete.success");
		el.setAttr("msg", msg);
		
		reply(el,wxproject_id);
	}
	
	private void update_news(EventLoader el,long wxproject_id) throws IOException, ServletException, SQLException{
		String event=el.getStr("event");
		long news_id=el.getLong("id");
		String description=el.getStr("description");
		String title=el.getStr("title");
		String url=el.getStr("url");
		int pos=el.getInt("pos");
		
		String msg=null;
		if(StringHelper.isNull(event)){
			el.response_to_root("/reply");
			return;
		}
		
		if(description.length()>Keys.getInt("auto_reply.news_msg_description_length")){
			msg=String.format(el.i18("replysetting.news.description.max.length.exceed"),Keys.getInt("auto_reply.news_msg_description_length"));
			el.setAttr("msg",msg);
			reply(el,wxproject_id);
			return;
		}
		
		if(title.length()>Keys.getInt("auto_reply.news_msg_title_length")){
			msg=String.format(el.i18("replysetting.news.title.max.length.exceed"),Keys.getInt("auto_reply.news_msg_title_length"));
			el.setAttr("msg",msg);
			reply(el,wxproject_id);
			return;
		}
		
		if(url.length()>Keys.getInt("auto_reply.url_max_length")){
			msg=String.format(el.i18("replysetting.news.url.max.length.exceed"),Keys.getInt("auto_reply.url_max_length"));
			el.setAttr("msg",msg);
			reply(el,wxproject_id);
			return;
		}
		
		MsgNews msg_news=auto_reply_news_dao.getById(news_id);
		if(msg_news==null){
			 msg=el.i18("replysetting.news.message.not.exist");
			 el.setAttr("msg",msg);
			 reply(el,wxproject_id);
			return;
		}
		
		MsgNews message=new MsgNews();
		message.setId(news_id);
		message.setDescription(description);
		message.setTitle(title);
		message.setPos(pos);
		message.setUrl(url);
		message.setWxproject_id(wxproject_id);
		auto_reply_news_dao.update(message);
		
		if(msg==null){
			msg=el.i18("replysetting.news.update.success");
		}
		el.setAttr("msg", msg);
		 reply(el,wxproject_id);
	}
	
	

	
	private void add_text(EventLoader el,long wxproject_id) throws IOException, SQLException, ServletException{
		String event=el.getStr("event");
		String msg_type=el.getStr("msg_type","event");
		if(StringHelper.isNull(event)){
			el.response_to_root("/reply");
			return;
		}
		
		String content=el.getStr("content");
		String msg=null;
		if(StringHelper.isNull(content)){
			msg=el.i18("replysetting.text.content.cannot.be.empty");
			el.setAttr("msg",msg);
			reply(el,wxproject_id);
			return;
		}
		
		if(content.length()>Keys.getInt("auto_reply.text_msg_conetnt_length")){
			msg=String.format(el.i18("replysetting.text.content.max.length.excceed"),Keys.getInt("auto_reply.text_msg_conetnt_length"));
			el.setAttr("msg",msg);
			reply(el,wxproject_id);
			return;
		}
		
		Message message=auto_reply_dao.getEventMessage(wxproject_id,event,msg_type);
		if(message !=null){
			msg=el.i18("replysetting.text.msg.only.need.one");
			el.setAttr("msg",msg);
			reply(el,wxproject_id);
			return;
		}
		message=new Message();
		message.setEvent(event);
		message.setContent(content);
		message.setInput("");
		message.setMsg_type(msg_type);
		message.setResponse_type("text");
		message.setWxproject_id(wxproject_id);
		auto_reply_dao.insert(message);
		if(msg==null){
			msg=el.i18("replysetting.msg.add.success");
		}
		el.setAttr("msg", msg);
		reply(el,wxproject_id);
	}
	
	private void update_text(EventLoader el,long wxproject_id) throws SQLException, IOException, ServletException{
		long id=el.getLong("id");
		String msg=null;
		
		String content=el.getStr("content");
		
		if(StringHelper.isNull(content)){
			msg=el.i18("replysetting.text.content.cannot.be.empty");
			el.setAttr("msg",msg);
			reply(el,wxproject_id);
			return;
		}
		
		if(content.length()>Keys.getInt("auto_reply.text_msg_conetnt_length")){
			msg=String.format(el.i18("replysetting.text.content.max.length.excceed"),Keys.getInt("auto_reply.text_msg_conetnt_length"));
			el.setAttr("msg",msg);
			reply(el,wxproject_id);
			return;
		}
		
		Message message=auto_reply_dao.getById(id);
		if(message ==null){
			msg=el.i18("replysetting.text.msg.not.exist");
			el.setAttr("msg",msg);
			reply(el,wxproject_id);
			return;
		}
		message.setContent(content);
		message.setResponse_type("text");
		message.setWxproject_id(wxproject_id);
		auto_reply_dao.update_text(message);
		if(msg==null){
			msg=el.i18("replysetting.msg.update.success");
		}
		el.setAttr("msg", msg);
		reply(el,wxproject_id);
		
	}
	
	private void delete_text(EventLoader el,long wxproject_id) throws IOException, ServletException, SQLException{
		long id=el.getLong("id");
		
		String msg=null;
		
		
		if(auto_reply_dao.getById(id)==null){
			msg=el.i18("replysetting.msg.delete.not.exists");
			el.setAttr("msg",msg);
			reply(el,wxproject_id);
			return;
		}
		
		auto_reply_dao.delete_by_id(id);
		if(msg==null){
			msg=el.i18("replysetting.msg.delete.success");
		}
		el.setAttr("msg", msg);
		reply(el,wxproject_id);
	}
	
}
